class CookieGame {
    constructor() {
        this.cookies = 0;
        this.totalCookies = 0;
        this.totalClicks = 0;
        this.cursors = 0;
        this.grandmas = 0;
        this.cursorCost = 15;
        this.grandmaCost = 100;
        this.cookiesPerSecond = 0;
        this.clickPower = 1;
        this.clickBonus = 0;
        this.combo = 1;
        this.maxCombo = 1;
        this.lastClickTime = 0;
        this.achievements = new Set();
        this.clickQueue = [];
        this.isProcessingClicks = false;
        this.lastUpdateTime = 0;
        this.particlePool = [];
        this.ripplePool = [];
        this.updateFrameId = null;
        this.statsUpdateTimer = null;

        // DOM元素
        this.initializeElements();
        this.initializeEventListeners();
        this.initializeParticlePool();
        this.startAutoProduction();
        this.loadGame();
        this.startAutoSave();
        this.updateAllStats();
        this.startRenderLoop();
    }

    initializeElements() {
        this.cookieElement = document.getElementById('cookie');
        this.cookieCountElement = document.getElementById('cookie-count');
        this.cookiesPerSecondElement = document.getElementById('cookies-per-second');
        this.cursorButton = document.getElementById('cursor-upgrade');
        this.grandmaButton = document.getElementById('grandma-upgrade');
        this.cursorCountElement = document.getElementById('cursor-count');
        this.grandmaCountElement = document.getElementById('grandma-count');
        this.particlesContainer = document.getElementById('particles-container');
        this.comboCounter = document.getElementById('combo-counter');
        this.cookiePower = document.getElementById('cookie-power');
        this.achievementContainer = document.getElementById('achievement-container');
        
        // 统计元素
        this.totalCookiesElement = document.getElementById('total-cookies');
        this.totalClicksElement = document.getElementById('total-clicks');
        this.maxComboElement = document.getElementById('max-combo');
        this.clickPowerElement = document.getElementById('click-power');
        this.clickBonusElement = document.getElementById('click-bonus');
        this.cursorProductionElement = document.getElementById('cursor-production');
        this.grandmaProductionElement = document.getElementById('grandma-production');
    }

    initializeParticlePool() {
        // 预创建粒子池
        for (let i = 0; i < 50; i++) {
            const particle = document.createElement('div');
            particle.className = 'click-particle';
            particle.style.display = 'none';
            this.particlePool.push(particle);
            this.particlesContainer.appendChild(particle);

            const ripple = document.createElement('div');
            ripple.className = 'ripple';
            ripple.style.display = 'none';
            this.ripplePool.push(ripple);
            this.particlesContainer.appendChild(ripple);
        }
    }

    getParticleFromPool() {
        return this.particlePool.find(p => p.style.display === 'none') || this.particlePool[0];
    }

    getRippleFromPool() {
        return this.ripplePool.find(r => r.style.display === 'none') || this.ripplePool[0];
    }

    initializeEventListeners() {
        const clickArea = document.querySelector('.cookie-click-area');
        
        // 使用节流处理点击事件
        let lastClickTime = 0;
        clickArea.addEventListener('click', (e) => {
            const now = performance.now();
            if (now - lastClickTime >= 16) { // 限制最高60fps
                const rect = clickArea.getBoundingClientRect();
                const x = e.clientX - rect.left;
                const y = e.clientY - rect.top;
                this.queueClick(x, y);
                lastClickTime = now;
            }
        });

        // 购买升级使用防抖
        this.cursorButton.addEventListener('click', this.debounce(() => this.buyCursor(), 100));
        this.grandmaButton.addEventListener('click', this.debounce(() => this.buyGrandma(), 100));

        // 优化键盘事件
        let spacePressed = false;
        document.addEventListener('keydown', (e) => {
            if (e.code === 'Space' && !spacePressed) {
                e.preventDefault();
                spacePressed = true;
                const rect = clickArea.getBoundingClientRect();
                const x = rect.width / 2;
                const y = rect.height / 2;
                this.queueClick(x, y);
            }
        });

        document.addEventListener('keyup', (e) => {
            if (e.code === 'Space') {
                spacePressed = false;
            }
        });

        // 添加悬停效果
        this.cookieElement.addEventListener('mouseover', () => {
            this.cookieElement.style.filter = 'brightness(1.1) drop-shadow(0 4px 8px rgba(0, 0, 0, 0.4))';
        });

        this.cookieElement.addEventListener('mouseout', () => {
            this.cookieElement.style.filter = 'drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3))';
        });
    }

    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func.apply(this, args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    startRenderLoop() {
        const render = () => {
            const now = performance.now();
            if (now - this.lastUpdateTime >= 16) { // 限制60fps
                this.updateAllStats();
                this.lastUpdateTime = now;
            }
            this.updateFrameId = requestAnimationFrame(render);
        };
        render();
    }

    queueClick(x, y) {
        this.clickQueue.push({ x, y, time: performance.now() });
        if (!this.isProcessingClicks) {
            this.processClickQueue();
        }
    }

    async processClickQueue() {
        this.isProcessingClicks = true;
        const now = performance.now();
        
        // 批量处理点击
        while (this.clickQueue.length > 0) {
            const clicks = this.clickQueue.splice(0, 10); // 每次处理最多10个点击
            await Promise.all(clicks.map(click => this.processClick(click.x, click.y)));
        }
        
        this.isProcessingClicks = false;
    }

    async processClick(x, y) {
        return new Promise(resolve => {
            this.updateCombo();
            const baseGain = this.clickPower * this.combo;
            this.cookies += baseGain;
            this.totalCookies += baseGain;
            this.totalClicks++;
            
            this.createParticle(x, y, baseGain);
            this.createRipple(x, y);
            
            // 使用 requestAnimationFrame 进行视觉更新
            requestAnimationFrame(resolve);
        });
    }

    createRipple(x, y) {
        const ripple = this.getRippleFromPool();
        ripple.style.display = 'block';
        ripple.style.left = x + 'px';
        ripple.style.top = y + 'px';
        ripple.style.transform = 'scale(0)';
        ripple.style.opacity = '1';

        requestAnimationFrame(() => {
            ripple.style.transform = 'scale(2)';
            ripple.style.opacity = '0';
        });
        
        setTimeout(() => {
            ripple.style.display = 'none';
        }, 800);
    }

    createParticle(x, y, value) {
        const particle = this.getParticleFromPool();
        particle.style.display = 'block';
        particle.textContent = '+' + value;
        
        const angle = Math.random() * Math.PI * 2;
        const distance = 50 + Math.random() * 50;
        const finalX = x + Math.cos(angle) * distance;
        const finalY = y - Math.sin(angle) * distance - 100;

        particle.style.left = x + 'px';
        particle.style.top = y + 'px';
        particle.style.transform = 'translate(0, 0)';
        particle.style.opacity = '1';

        requestAnimationFrame(() => {
            particle.style.transform = `translate(${finalX - x}px, ${finalY - y}px)`;
            particle.style.opacity = '0';
        });

        setTimeout(() => {
            particle.style.display = 'none';
        }, 1000);
    }

    updateCombo() {
        const now = performance.now();
        if (now - this.lastClickTime < 300) {
            this.combo = Math.min(this.combo + 1, 10);
        } else {
            this.combo = 1;
        }
        this.lastClickTime = now;
        
        if (this.combo > this.maxCombo) {
            this.maxCombo = this.combo;
            this.maxComboElement.textContent = this.maxCombo;
        }

        this.comboCounter.textContent = 'x' + this.combo;
        this.comboCounter.classList.add('active');
        setTimeout(() => this.comboCounter.classList.remove('active'), 300);
    }

    buyCursor() {
        if (this.cookies >= this.cursorCost) {
            this.cookies -= this.cursorCost;
            this.cursors++;
            this.cursorCost = Math.floor(this.cursorCost * 1.15);
            this.cookiesPerSecond = this.calculateCookiesPerSecond();
            this.updateAllStats();
            this.checkAchievements();
            
            const button = this.cursorButton;
            button.style.transform = 'scale(0.95)';
            setTimeout(() => button.style.transform = 'scale(1)', 100);
        }
    }

    buyGrandma() {
        if (this.cookies >= this.grandmaCost) {
            this.cookies -= this.grandmaCost;
            this.grandmas++;
            this.grandmaCost = Math.floor(this.grandmaCost * 1.15);
            this.cookiesPerSecond = this.calculateCookiesPerSecond();
            this.updateAllStats();
            this.checkAchievements();
            
            const button = this.grandmaButton;
            button.style.transform = 'scale(0.95)';
            setTimeout(() => button.style.transform = 'scale(1)', 100);
        }
    }

    calculateCookiesPerSecond() {
        return this.cursors * 0.1 + this.grandmas * 1;
    }

    updateAllStats() {
        // 使用 RAF 进行批量更新
        if (!this.statsUpdateTimer) {
            this.statsUpdateTimer = requestAnimationFrame(() => {
                this.cookieCountElement.textContent = Math.floor(this.cookies);
                this.cookiesPerSecondElement.textContent = this.cookiesPerSecond.toFixed(1);
                this.cursorCountElement.textContent = this.cursors;
                this.grandmaCountElement.textContent = this.grandmas;
                this.cursorButton.querySelector('.price').textContent = `价格: ${Math.floor(this.cursorCost)}`;
                this.grandmaButton.querySelector('.price').textContent = `价格: ${Math.floor(this.grandmaCost)}`;
                
                this.totalCookiesElement.textContent = Math.floor(this.totalCookies);
                this.totalClicksElement.textContent = this.totalClicks;
                this.maxComboElement.textContent = this.maxCombo;
                this.clickPowerElement.textContent = this.clickPower;
                this.clickBonusElement.textContent = this.clickBonus;
                this.cursorProductionElement.textContent = (this.cursors * 0.1).toFixed(1);
                this.grandmaProductionElement.textContent = this.grandmas;
                
                this.updateButtons();
                this.statsUpdateTimer = null;
            });
        }
    }

    updateButtons() {
        if (this.cookies >= this.cursorCost) {
            this.cursorButton.classList.add('can-buy');
            this.cursorButton.disabled = false;
        } else {
            this.cursorButton.classList.remove('can-buy');
            this.cursorButton.disabled = true;
        }

        if (this.cookies >= this.grandmaCost) {
            this.grandmaButton.classList.add('can-buy');
            this.grandmaButton.disabled = false;
        } else {
            this.grandmaButton.classList.remove('can-buy');
            this.grandmaButton.disabled = true;
        }
    }

    checkAchievements() {
        const achievements = [
            {
                id: 'first-cookie',
                condition: () => this.totalClicks >= 1,
                icon: '🍪',
                title: '第一块饼干',
                description: '点击获得第一块饼干'
            },
            {
                id: 'combo-master',
                condition: () => this.maxCombo >= 5,
                icon: '⚡',
                title: '连击大师',
                description: '达成5连击'
            },
            {
                id: 'cookie-empire',
                condition: () => this.totalCookies >= 1000,
                icon: '👑',
                title: '饼干帝国',
                description: '累计获得1000块饼干'
            },
            {
                id: 'grandma-army',
                condition: () => this.grandmas >= 5,
                icon: '👵',
                title: '奶奶军团',
                description: '拥有5个饼干奶奶'
            }
        ];

        achievements.forEach(achievement => {
            if (!this.achievements.has(achievement.id) && achievement.condition()) {
                this.achievements.add(achievement.id);
                this.showAchievement(achievement);
            }
        });
    }

    showAchievement(achievement) {
        const achievementElement = document.createElement('div');
        achievementElement.className = 'achievement';
        achievementElement.innerHTML = `
            <div class="achievement-icon">${achievement.icon}</div>
            <div class="achievement-info">
                <div class="achievement-title">${achievement.title}</div>
                <div class="achievement-desc">${achievement.description}</div>
            </div>
        `;

        this.achievementContainer.appendChild(achievementElement);
        setTimeout(() => achievementElement.classList.add('show'), 100);
        setTimeout(() => {
            achievementElement.classList.remove('show');
            setTimeout(() => achievementElement.remove(), 500);
        }, 3000);
    }

    startAutoProduction() {
        let lastTime = performance.now();
        const update = () => {
            const now = performance.now();
            const delta = (now - lastTime) / 1000; // 转换为秒
            
            if (this.cookiesPerSecond > 0) {
                const production = this.cookiesPerSecond * delta;
                this.cookies += production;
                this.totalCookies += production;
                
                // 降低自动生产粒子的频率
                if (Math.random() < 0.1) {
                    const rect = this.cookieElement.getBoundingClientRect();
                    const x = Math.random() * rect.width;
                    const y = Math.random() * rect.height;
                    this.createParticle(x, y, '+' + (production * 10).toFixed(1));
                }
            }
            
            lastTime = now;
            setTimeout(update, 100);
        };
        update();
    }

    saveGame() {
        const gameData = {
            cookies: this.cookies,
            totalCookies: this.totalCookies,
            totalClicks: this.totalClicks,
            cursors: this.cursors,
            grandmas: this.grandmas,
            cursorCost: this.cursorCost,
            grandmaCost: this.grandmaCost,
            cookiesPerSecond: this.cookiesPerSecond,
            clickPower: this.clickPower,
            clickBonus: this.clickBonus,
            maxCombo: this.maxCombo,
            achievements: Array.from(this.achievements)
        };
        localStorage.setItem('cookieGame', JSON.stringify(gameData));
    }

    loadGame() {
        const savedData = localStorage.getItem('cookieGame');
        if (savedData) {
            const gameData = JSON.parse(savedData);
            Object.assign(this, gameData);
            this.achievements = new Set(gameData.achievements);
            this.updateAllStats();
        }
    }

    startAutoSave() {
        setInterval(() => this.saveGame(), 30000);
    }

    cleanup() {
        // 清理资源
        cancelAnimationFrame(this.updateFrameId);
        clearTimeout(this.statsUpdateTimer);
        this.saveGame();
    }
}

// 启动游戏
window.onload = () => {
    const game = new CookieGame();
    window.addEventListener('beforeunload', () => game.cleanup());
}; 